import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/EmptyUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/date_util.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';

class CreateRWView extends BaseStatefulWidget {
  final Map rwMap;
  CreateRWView({this.rwMap});

  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return CreateRWViewState();
  }
}

class CreateRWViewState extends BaseState<YhpcViewModel, CreateRWView> {
  TextEditingController _pclxCtr = TextEditingController(); // 排查类型
  TextEditingController _pcbmCtr = TextEditingController(); // 排查部门
  TextEditingController _pcrCtr = TextEditingController(); // 排查人
  TextEditingController _pcrwmcCtr = TextEditingController(); // 排查任务名称
  TextEditingController _pcnrCtr = TextEditingController(); // 排查内容
  TextEditingController _pcnrmsCtr = TextEditingController(); // 排查内容描述
  TextEditingController _pckssjCtr = TextEditingController(); // 排查开始时间
  TextEditingController _pcjssjCtr = TextEditingController(); // 排查结束时间

  String _selOrgCode = ''; // 部门code
  String _selPclxId = ''; // 排查类型
  List _selPerson = [];
  List _pcnrList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _pckssjCtr.text = DateUtil.getDateStrByDateTime(DateTime.parse(DateTime.now().toString()),
        format: DateFormat.NORMAL);
    if (!EmptyUtils.isForEmpty(widget.rwMap)) {
      _initData();
    }
  }

  _initData() {
    _pclxCtr.text =
        StringUtils.getStr(widget.rwMap['hazardInvestigationTypeName']);
    _pcrwmcCtr.text = StringUtils.getStr(widget.rwMap['taskName']);
    _selPclxId = StringUtils.getStr(
        widget.rwMap['hazardInvestigationTypeId'].toString());

    _pcbmCtr.text = StringUtils.getStr(widget.rwMap['orgName']);
    _selOrgCode = StringUtils.getStr(widget.rwMap['orgCode'].toString());

    if (!EmptyUtils.isForEmpty(widget.rwMap['inspectorOpenIdList'])) {
      List _inspectorOpenIdList1 = widget.rwMap['inspectorOpenIdList'];
      _selPerson = _inspectorOpenIdList1;
    }
    if (!EmptyUtils.isForEmpty(widget.rwMap['inspectorOpenNameList'])) {
      List _inspectorOpenNameList1 = widget.rwMap['inspectorOpenNameList'];
      _pcrCtr.text = _getPerson1(_inspectorOpenNameList1);
    }

    _pcnrmsCtr.text = StringUtils.getStr(widget.rwMap['description']);
    _pckssjCtr.text = StringUtils.getStr(widget.rwMap['startTime']);
    _pcjssjCtr.text = StringUtils.getStr(widget.rwMap['endTime']);
  }

  @override
  Widget initWidget() {
    return Scaffold(
      resizeToAvoidBottomInset:true,
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '创建任务',
      ).create(),
      bottomSheet: BottomAppBar(),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                  color: SQColor.white),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    _commField(
                        isMust: true,
                        title: '排查类型',
                        hintText: '请选择排查类型',
                        isReadOnly: true,
                        controller: _pclxCtr,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, '/ChoosePclx')
                              .then((value) {
                            if (value != null) {
                              Map map1 = value;
                              _selPclxId = map1['id'].toString();
                              _pclxCtr.text =
                                  value == null ? '' : map1['typeName'];
                            }
                          });
                        }),
                    _commField(
                        isMust: true,
                        title: '排查部门',
                        hintText: '请选择排查部门',
                        isReadOnly: true,
                        controller: _pcbmCtr,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, '/ChooseBuMen')
                              .then((value) {
                            if (value != null) {
                              Map map1 = value;
                              _selOrgCode = map1['orgCode'];
                              _pcrCtr.text = '';
                              _selPerson = [];
                              _pcbmCtr.text =
                                  value == null ? '' : map1['orgName'];
                              _pcrwmcCtr.text = DateUtil.getDateStrByDateTime(
                                      DateTime.parse(DateTime.now().toString()),
                                      format: DateFormat
                                          .ZH_YEAR_MONTH_DAY) + DateUtil.getDateStrByDateTime(
                                      DateTime.parse(DateTime.now().toString()),
                                      format: DateFormat
                                          .ZH_HOUR_MINUTE) +
                                  _pcbmCtr.text +
                                  _pcrCtr.text +
                                  '的排查任务';
                            }
                          });
                        }),
                    _commField(
                        isMust: true,
                        title: '排查人',
                        hintText: '从排查部门中选择排查人',
                        isReadOnly: true,
                        controller: _pcrCtr,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          if (_selOrgCode.isEmpty) {
                            ToastUtils.showToast('请先选择排查部门');
                            return;
                          }
                          var _chooseMap = {
                            'selOrgCode': _selOrgCode,
                            'sel': _selPerson
                          };
                          Navigator.pushNamed(context, '/ChoosePerson',
                                  arguments: _chooseMap)
                              .then((value) {
                            if (value != null) {
                              _selPerson = value;
                              _pcrCtr.text = _getPerson(_selPerson);
                              if (_pcrCtr.text.contains(',')) {
                                var _pcary = _pcrCtr.text.split(",");
                                if (!EmptyUtils.isForEmpty(_pcary)) {
                                  _pcrwmcCtr
                                      .text = DateUtil.getDateStrByDateTime(
                                      DateTime.parse(DateTime.now().toString()),
                                      format: DateFormat
                                          .ZH_YEAR_MONTH_DAY) + DateUtil.getDateStrByDateTime(
                                      DateTime.parse(DateTime.now().toString()),
                                      format: DateFormat
                                          .ZH_HOUR_MINUTE) +
                                      _pcbmCtr.text +
                                      _pcary[0] +
                                      '等的排查任务';
                                }
                              } else {
                                _pcrwmcCtr.text = DateUtil.getDateStrByDateTime(
                                      DateTime.parse(DateTime.now().toString()),
                                      format: DateFormat
                                          .ZH_YEAR_MONTH_DAY) + DateUtil.getDateStrByDateTime(
                                      DateTime.parse(DateTime.now().toString()),
                                      format: DateFormat
                                          .ZH_HOUR_MINUTE) +
                                    _pcbmCtr.text +
                                    _pcrCtr.text +
                                    '的排查任务';
                              }
                            }
                          });
                        }),
                    _commField(
                        isMust: true,
                        title: '排查任务名称',
                        hintText: '请输入排查任务名称',
                        controller: _pcrwmcCtr),
                    _commField(
                        isMust: true,
                        title: '排查内容',
                        hintText: '请选择排查内容',
                        controller: _pcnrCtr,
                        isReadOnly: true,
                        suffixIcon: Icon(
                          Icons.arrow_forward_ios_outlined,
                          size: Dimens.dimens15,
                          color: SQColor.black_999999,
                        ),
                        onTap: () {
                          Navigator.pushNamed(context, '/ChoosePcnr')
                              .then((value) {
                            if (value != null) {
                              _pcnrList = value;
                              _pcnrCtr.text = '已选择';
                            }
                          });
                        }),
                    _commField(
                      title: '排查内容描述',
                      controller: _pcnrmsCtr,
                      hintText: '请输入排查内容描述',
                      maxLength: 200,
                    ),
                    _commField(
                        isMust: true,
                        controller: _pckssjCtr,
                        title: '排查开始时间',
                        hintText: '请选择排查开始时间',
                        isReadOnly: true,
                        suffixIcon: Image.asset(
                          "img/field_date.png",
                          width: Dimens.dimens15,
                          height: Dimens.dimens15,
                        ),
                        onTap: () {
                          _datePicker(true);
                        }),
                    _commField(
                        isMust: true,
                        controller: _pcjssjCtr,
                        title: '排查结束时间',
                        hintText: '请选择排查结束时间',
                        isReadOnly: true,
                        suffixIcon: Image.asset(
                          "img/field_date.png",
                          width: Dimens.dimens15,
                          height: Dimens.dimens15,
                        ),
                        onTap: () {
                          _datePicker(false);
                        }),
                  ],
                ),
              ),
            ),
          ),
          _bottomView()
        ],
      ),
    );
  }

  _datePicker(bool isStart) {
    String jbTime = '';
    showDatePicker(
      context: context,
      initialDate: new DateTime.now(), // 加 30 天
      firstDate:
          new DateTime.now().subtract(new Duration(days: 3650)), // 减 30 天
      lastDate: new DateTime.now().add(new Duration(days: 3650)),
    ).then((DateTime val) {
      showTimePicker(
        context: context,
        initialTime: new TimeOfDay.now(),
      ).then((val1) {
        if (val1 == null) {
          return;
        }
        setState(() {
          jbTime = DateUtil.getDateStrByDateTime(DateTime.parse(val.toString()),
              format: DateFormat.YEAR_MONTH_DAY);
          String hour1 = val1.hour < 10
              ? "0" + val1.hour.toString()
              : val1.hour.toString();
          String hour2 = val1.minute < 10
              ? "0" + val1.minute.toString()
              : val1.minute.toString();

          jbTime = jbTime +
              " " +
              hour1 +
              ":" +
              hour2 +
              ":" +
              "00"; // 2018-07-12 00:00:00.000018-07-12 00:00:00.000
          DateTime _currTime = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.parse(DateTime.now().toString()),
              format: DateFormat.YEAR_MONTH_DAY_HOUR_MINUTE));
          if (isStart) {
            DateTime _startTime = DateTime.parse(jbTime);
            if(_pckssjCtr.text.isNotEmpty) {
              if(_currTime.isAfter(_startTime)) {
                ToastUtils.showToast('排查开始时间不能早于当前时间');
                _pckssjCtr.text = DateUtil.getDateStrByDateTime(_currTime);
              }else {
                _pckssjCtr.text = jbTime;
              }
            }
            if (_pcjssjCtr.text.isNotEmpty) {
              DateTime jsxxTime = DateTime.parse(_pcjssjCtr.text);
              DateTime ksxxTime = DateTime.parse(_pckssjCtr.text);
                if (ksxxTime.isAfter(jsxxTime)) {
                  ToastUtils.showToast('排查开始时间不能大于排查结束时间');
                }else {
                  _pckssjCtr.text = jbTime;
                }
            }
          } else {
            if (_pckssjCtr.text.isEmpty) {
              ToastUtils.showToast('请先选择排查开始时间');
            } else {
              DateTime jsxxTime = DateTime.parse(jbTime);
              DateTime ksxxTime = DateTime.parse(_pckssjCtr.text);
              if (ksxxTime.isAfter(jsxxTime)) {
                ToastUtils.showToast('排查开始时间不能大于排查结束时间');
              }else {
                _pcjssjCtr.text = jbTime;
              }
            }
          }
        });
      }).catchError((err) {
        print(err);
      });
    }).catchError((err) {
      print(err);
    });
  }

  _getPerson(List list) {
    // 按逗号拼接
    String ids = '';
    for (var i = 0; i < list.length; i++) {
      String string = '';
      if (ids.length > 0) {
        string = '、';
      }
      ids = ids + string + list[i]['name'];
    }
    return ids;
  }

  _getPerson1(List list) {
    // 按逗号拼接
    String ids = '';
    for (var i = 0; i < list.length; i++) {
      String string = '';
      if (ids.length > 0) {
        string = '、';
      }
      ids = ids + string + list[i];
    }
    return ids;
  }

  _bottomView() {
    return InkWell(
      onTap: () {
        _submit();
      },
      child: SafeArea(
        child: Container(
          margin: EdgeInsets.only(left: 15, right: 15),
          height: 45,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: SQColor.blue_026FFF,
            borderRadius: BorderRadius.circular(10),
          ),
          child: JText('提交', color: Colors.white),
        ),
      ),
    );
  }

  _submit() {
    ToastUtils.showLoading();
    if (_pclxCtr.text.isEmpty ||
        _pcbmCtr.text.isEmpty ||
        _pcrCtr.text.isEmpty ||
        _pcrwmcCtr.text.isEmpty ||
        _pcnrCtr.text.isEmpty ||
        _pckssjCtr.text.isEmpty ||
        _pcjssjCtr.text.isEmpty) {
      ToastUtils.dissLoading();
      ToastUtils.showToast('请填写完整内容');
      return;
    }
    List inspectorOpenIdList = [];
    if (_selPerson.length > 0) {
      for (var i = 0; i < _selPerson.length; i++) {
        if (!EmptyUtils.isForEmpty(widget.rwMap)) {
          inspectorOpenIdList.add(_selPerson[i]);
        } else {
          inspectorOpenIdList.add(_selPerson[i]['openId']);
        }
      }
    }
    var map = {
      'id': "",
      'taskName': _pcrwmcCtr.text,
      'hazardInvestigationTypeId': _selPclxId,
      'orgCode': _selOrgCode,
      'inspectorOpenIdList': inspectorOpenIdList,
      'description': _pcnrmsCtr.text,
      'startTime': _pckssjCtr.text,
      'endTime': _pcjssjCtr.text,
      'hazardInvestigationRiskPointList': _pcnrList
    };
    viewModel.submitRw(map);
    viewModel.submitRwStream().listen((event) {
      ToastUtils.dissLoading();
      if (event['code'] == '0') {
        ToastUtils.showToast('提交成功');
        Navigator.pop(context);
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      ToastUtils.dissLoading();
      print(e);
    });
  }

  _commField(
      {bool isMust = false,
      String hintText = '',
      Widget suffixIcon,
      String title = '',
      bool isReadOnly = false,
      int maxLength,
      var onTap,
      var controller}) {
    return Container(
      margin: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            child: Row(
              children: [
                isMust
                    ? JText(
                        '* ',
                        color: SQColor.red,
                      )
                    : Container(),
                Container(
                  child: JText(title),
                ),
              ],
            ),
          ),
          Container(
            // alignment: Alignment.center,
            margin: EdgeInsets.only(top: 10),
            padding: EdgeInsets.only(
                left: 10,
                right: maxLength == null ? 0 : 10,
                bottom: maxLength == null ? 0 : 10),
            child: Center(child: ConstrainedBox(child:  TextField(
              onTap: onTap,
              controller: controller,
              maxLength: maxLength,
              style: TextStyle(fontSize: Dimens.textSize28),
              readOnly: isReadOnly,
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  suffixIcon: suffixIcon
              ),
            ), constraints: BoxConstraints(
              maxHeight: maxLength != null ? 60 : 45
            ),),),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: SQColor.lineE7E7E7,
              ),
              borderRadius: BorderRadius.all(Radius.circular(Dimens.dimens4)),
            ),
          ),
        ],
      ),
    );
  }
}
